package com.one.group.admin.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.one.group.admin.mapper.OwnerMapper;
import com.one.group.admin.mapper.SpHouseMapper;
import com.one.group.admin.mapper.SpRenterMapper;
import com.one.group.enums.ResultEnum;
import com.one.group.exception.BusinessException;
import com.one.group.model.dto.*;
import com.one.group.model.entity.Owner;
import com.one.group.model.entity.SpBuilding;
import com.one.group.model.entity.SpHouse;
import com.one.group.model.entity.SpRenter;
import com.one.group.model.vo.HouseManagementVo;
import com.one.group.model.vo.PayerInfoVo;
import com.one.group.model.vo.SpHouseVo;
import com.one.group.service.SpHouseService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@DubboService
@Service
public class SpHouseServiceImpl extends ServiceImpl<SpHouseMapper, SpHouse> implements SpHouseService {
    @Autowired
    private SpHouseMapper spHouseMapper;
    @Autowired
    private OwnerMapper ownerMapper;
    @Autowired
    private SpRenterMapper spRenterMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public List<HouseManagementVo> getHouseManagementList(Long buildingId) {
        //获取当前线程租户ID
        Long tenantId = Convert.toLong(StpUtil.getExtra("tenant_id"));
        return spHouseMapper.getHouseManagementList(buildingId,tenantId);
    }

    @Override
    public List<String> getunitList(Long buildingId) {
        //获取当前线程租户ID
        Long tenantId = Convert.toLong(StpUtil.getExtra("tenant_id"));
        return spHouseMapper.getunitList(buildingId,tenantId);
    }

    @Override
    public List<String> getfloorList(Long buildingId) {
        //获取当前线程租户ID
        Long tenantId = Convert.toLong(StpUtil.getExtra("tenant_id"));
        return spHouseMapper.getfloorList(buildingId,tenantId);
    }

    @Override
    public boolean myadd(SpHouseAddDto spHouseAddDto) {
        //构建实体类
        try{
            SpHouse spHouse = new SpHouse();
            spHouse.setNumber(spHouseAddDto.getHouseNum());
            if (spHouseAddDto.getFloorId()==null||spHouseAddDto.getFloorId()==0){
                return false;
            }
            if (spHouseAddDto.getUnitId()==null||spHouseAddDto.getUnitId()==0){
                return false;
            }
            spHouse.setUnitId(spHouseAddDto.getUnitId());
            spHouse.setFloorId(spHouseAddDto.getFloorId());
            spHouse.setOrientation(spHouseAddDto.getOrientation());
            spHouse.setFloorSpace(spHouseAddDto.getFloorSpace());
            spHouse.setInsideSpace(spHouseAddDto.getInsideSpace());
            spHouse.setSharedSpace(spHouseAddDto.getSharedSpace());
            spHouse.setRoom(spHouseAddDto.getRoom());
            spHouse.setHall(spHouseAddDto.getHall());
            spHouse.setToilet(spHouseAddDto.getToilet());
            rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
            rabbitTemplate.convertAndSend("gxa.direct","houseUpdate",spHouseAddDto.getUnitId());
            return save(spHouse);
        }catch (Exception e){
            return false;
        }

    }

    @Override
    public boolean myUpdate(SpHouseUpdateDto spHouseUpdateDto) {
        try{
            SpHouse spHouse = new SpHouse();
            spHouse.setId(spHouseUpdateDto.getId());
            spHouse.setNumber(spHouseUpdateDto.getHouseNum());
            spHouse.setFloorSpace(spHouseUpdateDto.getFloorSpace());
            spHouse.setInsideSpace(spHouseUpdateDto.getInsideSpace());
            spHouse.setSharedSpace(spHouseUpdateDto.getSharedSpace());
            spHouse.setRoom(spHouseUpdateDto.getRoom());
            spHouse.setHall(spHouseUpdateDto.getHall());
            spHouse.setToilet(spHouseUpdateDto.getToilet());
            SpHouse house = getMapper().selectOneById(spHouseUpdateDto.getId());
            rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
            rabbitTemplate.convertAndSend("gxa.direct","houseUpdate",house.getUnitId());
            return updateById(spHouse,true);
        }catch (Exception e){
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByBuildingId(Long buildingId) {
        try{
            rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
            rabbitTemplate.convertAndSend("gxa.direct","allHouseUpdate",1);
            return spHouseMapper.removeByBuildingId(buildingId);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addAllHouse(SpHouseAddPlusDto spHouseAddPlusDto) {
        try{
            //获取当前线程租户ID
            Long tenantId = Convert.toLong(StpUtil.getExtra("tenant_id"));
            //获取当前楼栋所有单元id列表
            List<Long> unitIds = spHouseMapper.getUnitIdsByBuildingId(spHouseAddPlusDto.getBuildingId());
            //获取当前楼栋所有楼层id列表
            List<Long> floorIds = spHouseMapper.getFloorIdsByBuildingId(spHouseAddPlusDto.getBuildingId());
            Long i = 1L;
            for (Long floorId : floorIds) {
                Long j = 1L;
                for (Long unitId : unitIds) {
                    //如果当前楼栋单元和楼层有房屋数据
                    if (spHouseMapper.getHouseCountByUnitIdAndFloorId(unitId,floorId)>0){
                        continue;
                    }
                    addHouse(spHouseAddPlusDto,i,j,floorId,unitId);
                    j++;
                }
                i++;
            }
            rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
            rabbitTemplate.convertAndSend("gxa.direct","allHouseUpdate",1);
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //根据房屋id添加业主id
    @Override
    public boolean addOwnerIdById(Long houseId, Long ownerId) {
        try {
            // 获取当前租户ID
            Long tenantId = Convert.toLong(StpUtil.getExtra("tenant_id"));
            
            // 检查房屋是否存在
            QueryWrapper queryWrapper = QueryWrapper.create().from(SpHouse.class);
            queryWrapper.eq(SpHouse::getId, houseId)
                       .eq(SpHouse::getTenantId, tenantId);
            SpHouse existingHouse = spHouseMapper.selectOneByQuery(queryWrapper);
            
            if (existingHouse == null) {
                throw new BusinessException(ResultEnum.DATA_NOT_EXIST.getCode(),"该房屋不存在！");
            }
            
            // 更新房屋的业主ID
            existingHouse.setOwnerId(ownerId);
            return updateById(existingHouse, true);
            
        } catch (Exception e) {
            throw new BusinessException(ResultEnum.DATA_PROCESS_ERROR.getCode(),"业主绑定房屋失败！");
        }
    }

    @Override
    public PayerInfoVo queryPersonnelByHouseId(QueryPersonnelDto queryPersonnelDto) {
        PayerInfoVo payerInfoVo = new PayerInfoVo();
        if(queryPersonnelDto.getRenterId() == null){
            Owner owner = ownerMapper.selectOneById(queryPersonnelDto.getOwnerId());
            payerInfoVo.setId(owner.getId());
            payerInfoVo.setName(owner.getName());
            payerInfoVo.setPhone(owner.getPhone());
            payerInfoVo.setEmail(owner.getEmail());
            payerInfoVo.setPayerType(1);
            return payerInfoVo;
        }else {
            SpRenter spRenter = spRenterMapper.selectOneById(queryPersonnelDto.getRenterId());
            payerInfoVo.setId(spRenter.getId());
            payerInfoVo.setName(spRenter.getName());
            payerInfoVo.setPhone(spRenter.getPhone());
            payerInfoVo.setEmail(spRenter.getEmail());
            payerInfoVo.setPayerType(2);
            return payerInfoVo;
        }
    }

    @Override
    public SpHouseVo queryHouseById(Long id) {
        try{
            SpHouseVo spHouseVo =getMapper().mySelectOneById(id);
            if(!ObjectUtil.isEmpty(spHouseVo)){
                return spHouseVo;
            }else throw new BusinessException(ResultEnum.DATA_NOT_EXIST.getCode(),"该房屋不存在！");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
//    @Autowired
//    private OwnerMapper ownerMapper;
    @Override
    public List<SpHouse> myListByOwnerId(Long ownerId) {
        try {
            //通过账户id查询用户id
            Long userId = this.getOwnerId(ownerId);
            if (userId == null){
                return null;
            }
            QueryWrapper from = QueryWrapper.create().from(SpHouse.class);
            from.eq(SpHouse::getOwnerId,userId);
            return getMapper().selectListByQuery(from);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Long getOwnerId(Long ownerId) {
        return ownerMapper.getIdByUserId(ownerId);
    }

    @Override
    public String myGetById(Long houseId) {
        return getMapper().mySelectOneById(houseId).toString();
    }

    @Override
    public String sendMail(String message, Long ownerId) {
        try{
            // 查询业主邮箱
            String email = ownerMapper.getEmailByOwnerId(ownerId);
            // 发送邮件
            SpSendEmailDto spSendEmailDto = new SpSendEmailDto();
            spSendEmailDto.setEmail(email);
            spSendEmailDto.setContent(message);
            rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
            rabbitTemplate.convertAndSend("gxa.direct","sendEmail", spSendEmailDto);
            return "发送成功";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void addHouse(SpHouseAddPlusDto spHouseAddPlusDto,Long x,Long j,Long floorId,Long unitId){
        for (int i = 0; i < spHouseAddPlusDto.getHouseNumberOFUnits(); i++) {
            SpHouse spHouse = new SpHouse();
            String houseNum = x.toString() + j.toString() + i;
            spHouse.setNumber(Integer.valueOf(houseNum));
            spHouse.setUnitId(unitId);
            spHouse.setFloorId(floorId);
            spHouse.setOrientation(spHouseAddPlusDto.getOrientation());
            spHouse.setFloorSpace(spHouseAddPlusDto.getFloorSpace());
            spHouse.setInsideSpace(spHouseAddPlusDto.getInsideSpace());
            spHouse.setSharedSpace(spHouseAddPlusDto.getSharedSpace());
            spHouse.setRoom(spHouseAddPlusDto.getRoom());
            spHouse.setHall(spHouseAddPlusDto.getHall());
            spHouse.setToilet(spHouseAddPlusDto.getToilet());
            rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
            rabbitTemplate.convertAndSend("gxa.direct","houseUpdate",spHouse.getUnitId());
            save(spHouse);
        }
    }
}
